package com.wzt.car.service.impl;

import com.wzt.base.service.impl.BaseServiceImpl;
import com.wzt.base.util.AjaxResponse;
import com.wzt.base.util.VelocityUtil;
import com.wzt.car.CarDto;
import com.wzt.car.domain.Car;
import com.wzt.car.domain.CarDetail;
import com.wzt.car.domain.CarOnlineAuditLog;
import com.wzt.car.domain.Type;
import com.wzt.car.es.doc.CarDoc;
import com.wzt.car.es.repository.CarDocRepository;
import com.wzt.car.mapper.CarDetailMapper;
import com.wzt.car.mapper.CarMapper;
import com.wzt.car.mapper.CarOnlineAuditLogMapper;
import com.wzt.car.mapper.TypeMapper;
import com.wzt.car.service.ICarService;
import com.wzt.org.domain.Shop;
import com.wzt.org.mapper.ShopMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wzt
 * @since 2022-09-09
 */
@Service
public class CarServiceImpl extends BaseServiceImpl<Car> implements ICarService {
    @Autowired
    private CarMapper carMapper;
    @Autowired
    private CarDetailMapper carDetailMapper;
    @Autowired
    private CarOnlineAuditLogMapper logMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private TypeMapper typeMapper;
    @Autowired
    private CarDocRepository carDocRepository;
    @Value("${portalWebsitePath}")
    String portalWebsitePath;

    /**
     * 添加车辆需要进行审核
     *
     * @param car
     */
    @Override
    public void addOne(Car car) {
        CarDetail carDetail = car.getCarDetail();
        /*审核*/
        // 车辆基本信息
        String baseInfo = car.getTitle() + " " + carDetail.getInfo();
        AjaxResponse ajaxResponse = AjaxResponse.oneResponse();
        // 审核日志
        CarOnlineAuditLog log = new CarOnlineAuditLog();
        // 设置审核时间
        log.setAuditTime(new Date());
        // 审核日志设置
        if (ajaxResponse.getSuccess()) {
            log.setState(1);
            log.setNote("系统审核通过！");
        } else {
            log.setState(-1);
            log.setNote("系统审核失败！" + ajaxResponse.getMessage());
        }

        // 保存车辆信息
        car.setCreatetime(new Date());
        car.setState(0L);
        car.setAuditstate(log.getState());
        carMapper.insert(car);

        // 保存carDetail信息
        carDetail.setCarId(car.getId());
        carDetail.setCartitle(car.getTitle());
        carDetailMapper.insert(carDetail);

        // 保存日志
        log.setCarId(car.getId());
        logMapper.insert(log);
    }

    /**
     * 上架车辆
     *
     * @param carDto
     */
    @Override
    public void onSale(CarDto carDto) {
        //参数判断
        List<Long> ids = carDto.getIds();
        if (ids == null || ids.size() < 1) {
            throw new RuntimeException("系统异常，参数不对！");
        }

        // 创建carDocs并保存到es中
        List<CarDoc> carDocs = buildCarDocs(ids);
        carDocRepository.saveAll(carDocs);

        //修改数据库状态和上架时间
        carMapper.putaway(ids);

        //添加日志
        addLogs(carDto, 2);

        // 产生静态化页面
        staticizePage(carDto.getIds());
    }

    /**
     * 下架车辆
     *
     * @param carDto
     */
    @Override
    public void offSale(CarDto carDto) {
        // 参数判断
        List<Long> ids = carDto.getIds();
        if (ids == null || ids.size() < 1) {
            throw new RuntimeException("系统异常，参数不对！");
        }
        // es中删除数据
        List<CarDoc> carDocs = new ArrayList<>();
        ids.forEach(id -> {
            CarDoc doc = new CarDoc();
            doc.setId(id);

            // 删除对应车辆细节的静态页面
            File staticHtml = new File(portalWebsitePath + id + ".html");
            staticHtml.delete();
        });

        carDocRepository.deleteAll(carDocs);

        //修改数据库状态和下架时间
        carMapper.soldOut(carDto.getIds());

        //添加日志
        addLogs(carDto, 3);
    }

    /**
     * 创建CarDoc集合
     *
     * @param ids
     * @return
     */
    private List<CarDoc> buildCarDocs(List<Long> ids) {
        List<CarDoc> carDocs = new ArrayList<>();
        ids.forEach(carId -> {
            carDocs.add(buildCarDoc(carId));
        });
        return carDocs;
    }

    /**
     * 创建单个CarDoc
     *
     * @param carId
     * @return
     */
    private CarDoc buildCarDoc(Long carId) {
        Car car = carMapper.loadById(carId);
        CarDoc carDoc = new CarDoc();

        carDoc.setId(carId);
        carDoc.setTitle(car.getTitle());
        carDoc.setCover(car.getCover());
        carDoc.setSaleprice(car.getSaleprice());
        carDoc.setCostprice(car.getCostprice());
        carDoc.setIsnew(car.getIsnew());
        carDoc.setReigstertime(car.getReigstertime());
        carDoc.setMileage(car.getMileage());
        Shop shop = shopMapper.loadById(car.getShopId());
        carDoc.setShopId(shop.getId());
        carDoc.setShopName(shop.getName());
        carDoc.setShopAdress(shop.getAddress());
        carDoc.setOnsaletime(car.getOnsaletime());
        carDoc.setCosteffective(car.getCosteffective());
        carDoc.setRushsale(car.getRushsale());
        carDoc.setQuasinewcar(car.getQuasinewcar());
        carDoc.setTransitivecountry(car.getTransitivecountry());
        Type carType = typeMapper.loadById(car.getTypeId());
        carDoc.setTypeId(carType.getId());
        carDoc.setTypeName(carType.getName());
        CarDetail detail = carDetailMapper.loadByCarId(carId);
        if (detail != null) {
            carDoc.setCarInfo(detail.getInfo());
        }
        return carDoc;
    }

    /**
     * 日志信息记录
     * @param carOprDto
     * @param state
     */
    private void addLogs(CarDto carOprDto, int state) {
        List<CarOnlineAuditLog> logs = new ArrayList<>();
        carOprDto.getIds().forEach(id -> {
            CarOnlineAuditLog log = new CarOnlineAuditLog();
            log.setCarId(id);
            log.setState(state);//上架
            log.setAuditId(carOprDto.getOperatorId());
            log.setAuditTime(new Date());
            if (state == 2) {
                log.setNote(carOprDto.getOperatorName() + "对id为" + id + "进行了上架！");
            } else if (state == 3) {
                log.setNote(carOprDto.getOperatorName() + "对id为" + id + "进行了下架！");
            }
            logs.add(log);
        });

        logMapper.bulkSave(logs);
    }

    /**
     * 静态化页面
     * @param ids
     */
    private void staticizePage(List<Long> ids) {
        ids.forEach(id -> {
            //模型 car
            Car car = carMapper.loadById(id);

            //模板
            String tmplatePath = this.getClass().getClassLoader().getResource("").getPath()
                    +"/templates/carDetail.vm";

            //静态化页面生成的路径

            String htmlFilePath =portalWebsitePath + id+ ".html";
            VelocityUtil.staticByTemplate(car,tmplatePath,htmlFilePath);
        });
    }
}
